<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use App\Http\Controllers\Controller;

use App\Http\Models\Post;
use App\Http\Models\PostCid;
use App\Http\Models\Menu;
use App\Http\Models\Config;

class QueryController extends Controller {

    public function hello(){

    }

    public function postsCat(){
        $category = PostCid::get();
        return $category;
    }

    public function menus()
    {
        return $this->getMenuList();

    }

    private function getMenuList(){
        $all = Menu::all()->toArray();
        $menus = [];

        foreach($all as $key => $val){
            $menus[$val['id']] = $val;
        }

        $menus = $this->listMenuToTree($menus);
        return $menus;
    }

    //不是真正的树 树的效率没有这个高 本方法只需要遍历一遍 复杂度O(n)
    private function listMenuToTree( $listMenu )
    {
        foreach( $listMenu as $key => $val ){
            if(isset($listMenu[$val['pid']])){
                if(!@is_array($listMenu[$val['pid']]['sub'])) {
                    $listMenu[$val['pid']]['sub'] = array();
                }
                array_push($listMenu[$val['pid']]['sub'],$val);
            }
        }
        return $listMenu;
    }



    public function config($key)
    {
        $config =  Config::where('ckey',$key)->first();;
        if($config) return $config->cval;
        else return '';
    }
}
